package handler

import (
	"errors"
	"log"
	"strconv"
	"strings"

	"org.knight/api"
	"org.knight/data"
)

type IEIdCaptureHandler struct {
}

func (ic *IEIdCaptureHandler) Handle(c *api.Context) {
	//fmt.Println("try capture ie identity")
	//fmt.Printf("%v", c.E.P)

	var builder strings.Builder
	for i, run := range c.E.P.Runs() {
		if i > 5 {
			break
		}
		builder.WriteString(run.Text())
	}

	str := builder.String()

	//log.Printf("%s \n", str)
	j := strings.Index(str, "\t")

	if j > -1 {
		label, err := ParseLabel(str)
		if err != nil {
			return
		}
		if c.IE != nil {
			//摘掉当前IE
			//发布到
			//log.Printf("pushing %s to channel \n", c.IE)
			c.IE.Name = c.IE.Label.Name
			c.IE.SpecId = c.SpecId
			c.ReadyQueue <- *c.IE
		}
		c.IE = new(data.InfoElement)
		c.IE.Label = label
		//log.Printf("capatured label %v", label)

		//unset event since it has been consumed
		c.E = nil
	}
	//log.Printf("skip header parse ")

}

func ParseLabel(str string) (*data.Label, error) {
	label := new(data.Label)
	fragments := strings.Split(str, "\t")
	seg := strings.Split(fragments[0], ".")
	if len(seg) < 2 {
		return label, errors.New("not a label")
	}

	label.Name = strings.Join(fragments[1:], " ")

	chapt, err := strconv.ParseInt(seg[0], 0, 16)
	if err != nil {
		log.Printf("%s is not a label", str)
		return label, err
	}
	label.Chapter = int16(chapt)
	unit, err := strconv.ParseInt(seg[1], 0, 16)
	if err != nil {
		log.Printf("%s is not a label", str)
		return label, err
	}
	label.Unit = int16(unit)
	if len(seg) > 2 {
		sec, err := strconv.ParseInt(seg[2], 0, 16)
		if err != nil {
			//log.Printf("%s is not a label", str)
			return label, err
		}
		label.Section = int16(sec)
	}

	if len(seg) > 3 {
		label.Item = seg[3]
	}

	return label, nil
}
